# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import typing as t

from ksai.document.context import DocumentSection
from ksai.document.extractor.extractor import AbstractDocumentExtractor, DocumentExtractorException
from ksai.persistence.storage.attachment import Attachment


class PropertiesDocumentExtractor(AbstractDocumentExtractor):

    def __init__(self):
        super().__init__()

    def do_extract(self, attachment: Attachment) -> t.List[DocumentSection]:
        try:
            lines = attachment.content_string.splitlines()
            result = []
            for line in lines:
                line = line.strip()
                if not line or line.startswith("#") or line.startswith("!"):
                    result.append(line)
                    continue
                if "=" in line:
                    key, value = line.split("=", 1)
                elif ":" in line:
                    key, value = line.split(":", 1)
                else:
                    key, value = line, ""

                result.append(f"{key.strip()}: {value.strip()}")

            return [DocumentSection(text="\n".join(result))]
        except Exception as e:
            raise DocumentExtractorException(f"Extract properties file error: {e}") from e

    def extensions(self) -> t.List[str]:
        return ["properties"]

    def mimes(self) -> t.List[str]:
        return ["text/properties"]
